{% extends "rules/base.html" %}
{% block content %}
    <div class="container-fluid">
        {% if elasticsearch %}
            <script>
$(document).ready(function(){
    $('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
        localStorage.setItem('esstatsactiveTab', $(e.target).attr('href'));

        if ($(e.target).attr('href') === '#cluster') {
            setTimeout(get_es_stats, 100);
        }
    });
    var activeTab = localStorage.getItem('esstatsactiveTab');
    if(activeTab){
        $('#estats a[href="' + activeTab + '"]').tab('show');
    }
});
            </script>
            <div role="tabpanel">
                <!-- Nav tabs -->
                <ul class="nav nav-tabs" id="estats" role="tablist">
                    <li role="presentation" class="active">
                        <a href="#cluster" aria-controls="cluster" role="tab" data-toggle="tab">Cluster info</a>
                    </li>
                    <li role="presentation">
                        <a href="#indices" aria-controls="indices" role="tab" data-toggle="tab">Indices stats</a>
                    </li>
                    {% if logstash_stats %}
                        <li role="presentation">
                            <a href="#logstash-panel"
                               aria-controls="logstash-panel"
                               role="tab"
                               data-toggle="tab">Logstash insertion speed</a>
                        </li>
                    {% endif %}
                    <li role="presentation">
                        <a href="#errors" aria-controls="errors" role="tab" data-toggle="tab">Shards</a>
                    </li>
                </ul>
                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane fade in active" id="cluster">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="panel panel-default" id="shards">
                                    <div class="panel-heading">
                                        <h2 class="panel-title">Data shards</h2>
                                    </div>
                                    <div class="panel-body">
                                        <ul>
                                            <li>
                                                <span class="type">Active primary shards:</span>
                                                <span class="label label-default pull-right" id="active_primary_shards">N/A</span>
                                            </li>
                                            <li>
                                                <span class="type">Active shards:</span>
                                                <span class="label label-default pull-right" id="active_shards">N/A</span>
                                            </li>
                                            <li>
                                                <span class="type">Relocating shards:</span>
                                                <span class="label label-default pull-right" id="relocating_shards">N/A</span>
                                            </li>
                                            <li>
                                                <span class="type">Initializing shards:</span>
                                                <span class="label label-default pull-right" id="initializing_shards">N/A</span>
                                            </li>
                                            <li>
                                                <span class="type">Unassigned shards:</span>
                                                <span class="label label-default pull-right" id="unassigned_shards">N/A</span>
                                            </li>
                                        </ul>
                                    </div>
                                    <!-- panel-body -->
                                </div>
                                <!-- panel -->
                            </div>
                            <!-- col -->
                            <div class="col-md-4">
                                <div class="panel panel-default" id="docs">
                                    <div class="panel-heading">
                                        <h2 class="panel-title">Documents/entries info</h2>
                                    </div>
                                    <div class="panel-body">
                                        <ul>
                                            <li>
                                                <span class="type">Nb of documents:</span>
                                                <span class="pull-right label label-default" id="docs_count">N/A</span>
                                            </li>
                                            <li>
                                                <span class="type">Nb of deletions:</span>
                                                <span class="pull-right label label-default" id="docs_deleted">N/A</span>
                                            </li>
                                        </ul>
                                    </div>
                                    <!-- panel-body -->
                                </div>
                                <!-- panel -->
                            </div>
                            <!-- col -->
                        </div>
                        <!-- row -->
                        <div class="row">
                            <div class="col-md-4">
                                <div class="panel panel-default" id="nodes">
                                    <div class="panel-heading">
                                        <h2 class="panel-title">Nodes info</h2>
                                    </div>
                                    <div class="panel-body">
                                        <ul>
                                            <li>
                                                <span class="type">Number of nodes:</span>
                                                <span class="pull-right label label-default" id="nb_nodes">N/A</span>
                                            </li>
                                            <li>
                                                <span class="type">Number of data nodes:</span>
                                                <span class="pull-right label label-default" id="nb_data_nodes">N/A</span>
                                            </li>
                                        </ul>
                                    </div>
                                    <!-- panel-body -->
                                </div>
                                <!-- panel -->
                            </div>
                            <!-- col -->
                            <div class="col-md-4">
                                <div class="container-fluid container-cards-pf">
                                    <div class="row row-cards-pf">
                                        <div class="col-xs-12 col-sm-12 col-md-12">
                                            <div class="card-pf card-pf-utilization">
                                                <h2 class="card-pf-title">Filesystem</h2>
                                                <div class="card-pf-body" id="fs">
                                                    <p class="card-pf-utilization-details">
                                                        <span class="card-pf-utilization-card-details-count" id="fs_free"></span>
                                                        <span class="card-pf-utilization-card-details-description">
                                                            <span class="card-pf-utilization-card-details-line-1">
                                                                Available
                                                            </span>
                                                            <span class="card-pf-utilization-card-details-line-2">
                                                                of
                                                                <span id="fs_total">
                                                                </span>
                                                            </span>
                                                        </span>
                                                    </p>
                                                    <div id="chart-pf-donut-fs">
                                                    </div>
                                                    <script>
                                                    </script>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- /row -->
                                </div>
                                <!-- /container -->
                            </div>
                            <!-- col -->
                        </div>
                        <!-- row -->
                    </div>
                    <div role="tabpanel" class="tab-pane fade in" id="indices">
                        <div class="row">
                            <div class="col-md-12">
                                <div id="indices_stats">
                                    Fetching data
                                </div>
                            </div>
                        </div>
                    </div>
                    {% if logstash_stats %}
                        <div role="tabpanel" class="tab-pane fade in" id="logstash-panel">
                            <div class="row">
                                <div class="col-md-12">
                                    <h2>
                                        Logstash event insertion speed
                                    </h2>
                                    <p id="logstash_title"/>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div id="logstash">
                                        <span>
                                            Fetching data...
                                        </span>
                                        <svg style="width:100%;height:300px">
                                        </svg>
                                    </div>
                                </div>
                                <!-- col -->
                            </div>
                            <!-- row -->
                        </div>
                    {% endif %}
                    <div role="tabpanel" class="tab-pane fade in" id="errors">
                        <div id="read_only" style="display: none;">
                            <div class="row">
                                <div class="col-md-12">
                                    <h3 class="text-danger">ES is in Read Only mode</h3>
                                    {% if maintenance_tasks and perms.rules.configuration_edit %}
                                        Elasticsearch has exceeded the watermark parameter of free space (95%), please adapt log retention parameters in <a href="{% url 'global_settings' %}">Global settings </a> , then switch the cluster back to Read/Write mode in the <a href="{% url 'maintenance_tasks' %}">Maintenance page </a>.
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <h2>Shards</h2>
                                <pre id="es_shards">
                                    Fetching data
                                </pre>
                                <h2>Unassigned shards with explanations</h2>
                                <pre id="es_explains" style="white-space: pre-wrap;">
                                    Fetching data
                                </pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <script>
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

function get_es_stats() {
    $.ajax({
        type:"GET",
        url: "{% url 'es_stats' %}",
        success: function(data) {
            if (!data) {
                $("#es_status").removeClass("label-default");
                $("#es_status").removeClass("label-warning");
                $("#es_status").removeClass("label-success");
                $("#es_status").addClass("label-danger");
                $("#es_status").text("red");
            } else {
                $("#docs_count").text(data['indices']['docs']['count']);
                $("#docs_deleted").text(data['indices']['docs']['deleted']);
                var data_size = data['indices']['store']['size_in_bytes'];
                var fs_total = data['nodes']['fs']['total_in_bytes'];
                $("#fs_total").text(bytesToSize(fs_total));
                var fs_free = data['nodes']['fs']['free_in_bytes'];
                $("#fs_free").text(bytesToSize(fs_free));
                $("#es_version").text(data['nodes']['versions']);
                $("#es_status").text(data['status']);
                $("#es_status").removeClass("label-warning");
                $("#es_status").removeClass("label-success");
                $("#es_status").removeClass("label-danger");
                $("#es_status").removeClass("label-default");
                if (data['status'] == 'green') {
                    $("#es_status").addClass("label-success");
                } else if (data['status'] == 'yellow') {
                    $("#es_status").addClass("label-warning");
                } else if (data['status'] == 'red') {
                    $("#es_status").addClass("label-danger");
                }
                if (data['read_only']) {
                    $("#read_only").show();
                } else {
                    $("#read_only").hide();
                }
                var c3ChartDefaults = $().c3ChartDefaults();

                var donutConfig = c3ChartDefaults.getDefaultDonutConfig('A');
                donutConfig.bindto = '#chart-pf-donut-fs';
                var data_size_percent = 1.0 * data_size / fs_total * 100;
                var fs_free_percent = 1.0 * fs_free / fs_total * 100;
                var fs_used_percent = 100.0 * ( 1 - 1.0 * fs_free / fs_total) - data_size_percent;
                donutConfig.color =  {
                      pattern: ["red", "#EC7A08","#D1D1D1"]
                };
                donutConfig.data = {
                    type: "donut",
                    columns: [
                        ["ES Data", data_size_percent],
                        ["Used", fs_used_percent],
                        ["Available", fs_free_percent]
                    ],
                    groups: [
                        ["data", "used", "available"]
                    ],
                    order: null
                };
                donutConfig.tooltip = {
                    contents: function (d) {
                        return '<span class="donut-tooltip-pf" style="white-space: nowrap;">' +
                                Math.round(d[0].ratio * 100) + '% ' + d[0].name +
                                '</span>';
                      }
                };

                var chart1 = c3.generate(donutConfig);
                var donutChartTitle = d3.select("#chart-pf-donut-fs").select('text.c3-chart-arcs-title');
                donutChartTitle.text("");
                datasize = bytesToSize(data['indices']['store']['size_in_bytes']);
                donutChartTitle.insert('tspan').text(datasize).classed('donut-title-big-pf', true).attr('dy', 0).attr('x', 0);
                donutChartTitle.insert('tspan').text("of ES data").classed('donut-title-small-pf', true).attr('dy', 20).attr('x', 0);

            }
        },
        error: function(data) {
            $("#es_status").removeClass("label-default");
            $("#es_status").removeClass("label-warning");
            $("#es_status").removeClass("label-success");
            $("#es_status").addClass("label-danger");
            $("#es_status").text("red");
        },
        complete: function() {
            setTimeout(get_es_stats, 30000);
        },
        timeout: 15000,
    });
}

function get_es_shard_stats() {
    $.ajax({
        type:"GET",
        url: "{% url 'es_shard_stats' %}",
        success: function(data) {
            if (data) {
                if (data.shards.length > 0) {
                    $("#es_shards").text(data.shards);
                } else {
                    $("#es_shards").text('No data');
                }

                if (data.explains.length > 0) {
                    $("#es_explains").text(data.explains);
                } else {
                    $("#es_explains").text('No data');
                }
            }
        },
        complete: function() {
            setTimeout(get_es_shard_stats, 120000);
        }
    });
}
$( 'document' ).ready(function() {
    get_es_stats();
    get_es_shard_stats();
});


function set_critical_value(data, selector) {
$("#".concat(selector)).text(data[selector]);
$("#".concat(selector)).removeClass("label-default");
$("#".concat(selector)).removeClass("label-warning");
$("#".concat(selector)).removeClass("label-success");
$("#".concat(selector)).removeClass("label-danger");
if (data[selector] > 0) {
$("#".concat(selector)).addClass("label-warning");
} else {
$("#".concat(selector)).addClass("label-success");
}
}

function get_es_detailed_health() {
    $.ajax({
        type:"GET",
        url: "{% url 'es_health' %}",
        success: function(data) {
            if (!data) {
                $("#es_status").removeClass("label-default");
                $("#es_status").addClass("label-danger");
            } else {
                $("#active_primary_shards").text(data['active_primary_shards']);
                $("#active_shards").text(data['active_shards']);
                set_critical_value(data, "relocating_shards");
                set_critical_value(data, "initializing_shards");
                set_critical_value(data, "unassigned_shards");
                $("#nb_nodes").text(data['number_of_nodes']);
                $("#nb_data_nodes").text(data['number_of_data_nodes']);
                $("#es_cluster_name").text(data['cluster_name']);
            }
        },
        error: function(data) {
            $("#es_status").removeClass("label-default");
            $("#es_status").addClass("label-danger");
        },
        complete: function() {
            setTimeout(get_es_detailed_health, 30000);
        },
        timeout: 15000,
    });
}

$( 'document' ).ready(get_es_detailed_health());

function get_es_indices_stats() {
    var indices_url = "{% url 'elasticsearch' %}?query=indices";
    if ((new URL(window.location.href)).searchParams.get('query')) {
        indices_url = window.location.href;
    } else {
        var page_no = new RegExp('[\?&]page=([^&#]*)').exec(window.location.href);
        if (page_no != null) {
            indices_url += '&page=' + page_no[1];
        }
    }

    $.ajax({
        type:"GET",
        url:indices_url,
        success: function(data) {
            $("#indices_stats").empty();
            $("#indices_stats").append(data);
        },
        error: function(data) {
            $("#indices_stats").text("Could not fetch data");
        },
        complete: function() {
            setTimeout(get_es_indices_stats, 30000);
        },
        timeout: 15000,
    });
}

{% if perms.rules.configuration_view %}$( 'document' ).ready(get_es_indices_stats());{% endif %}
{% if logstash_stats %}
    let loggers = null;
    {% if loggers %}
        loggers = {{ loggers|safe }};
    {% endif %}
    $( 'document' ).ready(draw_stats_timeline({{ from_date }}, 'eve_insert.rate_1m', '#logstash', 0, loggers, 'Events per second', stacked=true));
{% endif %}
</script>
    {% else %}
        <div class="alert alert-warning">
            Nothing to see here if you don't enable elasticsearch.
        </div>
    {% endif %}
    </div>
    <!-- container -->
{% endblock content %}
{% block sidebar %}
    <div class="panel-heading">
        <h2 class="panel-title">
            Elasticsearch
        </h2>
    </div>
    <div class="panel-body">
        <ul>
            <li>
                <span class="type">
                    Status:
                </span>
                <span class="pull-right label label-default" id="es_status">
                    Checking
                </span>
            </li>
            <li>
                <span class="type">
                    Cluster name:
                </span>
                <span class="pull-right" id="es_cluster_name">
                    N/A
                </span>
            </li>
            <li>
                <span class="type">
                    Version:
                </span>
                <span class="pull-right text-info" id="es_version">
                    N/A
                </span>
            </li>
        </ul>
    </div>
{% endblock sidebar %}
